<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;
use Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use App\Model\Admin;

class AdminsRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }


    public function addValidator()
    {

        Validator::extend('name_is_had', function ($attribute, $value, $parameters, $validator) {
            $count = Admin::where('username', $value)->count('*');
            if ($count > 0) {
                return false;
            }
            return true;

        });

    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $this->addValidator();
        return [
            'username' => [
                'sometimes',
                'required',
                'between:3,20',
                'regex:/^[a-zA-Z_][a-zA-Z0-9_]*$/',
                'name_is_had'
            ],
            'password' => [
                'sometimes',
                'required',
                'between:8,20',
                'regex:/^[a-zA-Z0-9_]*$/',
                'confirmed',
            ],
            'password_conformation' => 'sometimes|required',
        ];
    }

    public function messages()
    {
        return [
            'username.required' => '用户名不能为空',
            'username.between' => '长度在3-20个字符之间',
            'username.regex' => '用户名只能由数字字母下划线组成，且不能以数字开头',
            'username.name_is_had' => '此用户名已存在',

            'password.required' => '密码不能为空',
            'password.between' => '密码长度必须在8-20个字符之间',
            'password.regex' => '密码只能由数字字母下划线组成',
            'password.confirmed' => '再次密码不一致',

            'password_conformation' => '确认密码不能为空'
        ];
    }

    public function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
    {
        throw (new HttpResponseException(response()->json([
            'status_code' => 500,
            'error' => $validator->errors()->all(),
        ], 200)));
    }
}
